package XMLCreator;

import java.io.File;
import java.util.LinkedList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public abstract class XMLReader<T> {
	
	public LinkedList<T> read(String name){
		
		try {
			File file = new File(name);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(file);
			doc.getDocumentElement().normalize();
			NodeList nodeLst = doc.getElementsByTagName(getElementType());

			LinkedList<T> ans=new LinkedList<T>();
			
			for (int s = 0; s < nodeLst.getLength(); s++) {
				Node fstNode = nodeLst.item(s);

				if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
					Element fstElmnt = (Element) fstNode;
					ans.add(makeElement(fstElmnt));
				}				
			}
			return ans;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
			System.out.println("Error in XMLReader");//TODO XMLReader
		}		
		return null;
	}

	abstract protected T makeElement(Element fstElmnt);
	abstract protected String getElementType();
	
	protected String getValue(String field,Element fstElmnt){
		NodeList lstNmElmntLst = fstElmnt.getElementsByTagName(field);
		Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
		if (lstNmElmnt==null)
			return null;
		NodeList lstNm = lstNmElmnt.getChildNodes();
		return ((Node) lstNm.item(0)).getNodeValue();		
	}
}
